﻿from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from django.core.urlresolvers import reverse
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.db.models import Q
from userprofile.models import UserProfile, Friendship
from userprofile.forms import UserProfileMainForm, UserProfileContactsForm, UserProfileSearchForm
from geography.models import *
from geography.forms import PlaceFormSet
from context_processor import user_context
from jinja2_shortcuts import render_to_response

def add_friendship(request, id=None):
    new_friend = get_object_or_404(UserProfile, pk=id)
    try:
        new_fship = Friendship(_from=request.profile, _to=new_friend)
        new_fship.save()
    except:
        pass
    return HttpResponseRedirect(reverse(view_profile, args=[str(id)]))

def allow_friendship(request, id=None):
    profile = request.profile
    new_friendship = get_object_or_404(Friendship, _from=id)
    profile.friends.add(new_friendship._from)
    profile.save()
    new_friendship.delete()
    return HttpResponseRedirect(reverse(view_profile, args=[str(id)]))

def deny_friendship(request, id=None):
    new_friendship = get_object_or_404(Friendship, _from=id)
    new_friendship.delete()
    return HttpResponseRedirect(reverse(view_profile, args=[str(id)]))

def delete_friendship(request, id=None):
    profile = request.profile
    lost_friend = get_object_or_404(UserProfile, pk=id)
    profile.friends.remove(lost_friend)
    return HttpResponseRedirect(reverse(view_profile, args=[str(id)]))

def edit_profile(request, template_name):
    #
    # Редактирование текущего профиля
    #
    success = []
    errors = []
    profile = request.profile
    if request.method == 'POST':
        mainForm = UserProfileMainForm(request.POST, instance=profile)
        contactsForm = UserProfileContactsForm(request.POST, instance=profile)
        placeFormSet = PlaceFormSet(request.POST)
        
        if mainForm.is_valid():
            mainForm.save()
        else:
            errors.append(u'Исправьте ошибки в форме «Информация о себе»')
            
        if contactsForm.is_valid():
            contactsForm.clean()
            contacts = contactsForm.save()
        else:
            errors.append(u'Исправьте ошибки в форме «Контакты»')
        if placeFormSet.is_valid():
            instances = placeFormSet.save(commit=False)
            for i in instances:
                i.save()
                profile.places.add(i)
            for i in placeFormSet.deleted_objects:
                profile.places.remove(i)           
        else:
            errors.append(u'Исправьте ошибки в форме «Места»')
    
    mainForm = UserProfileMainForm(instance=profile)
    contactsForm = UserProfileContactsForm(instance=profile)
    placeFormSet = PlaceFormSet(queryset=profile.places.all())     
           
    return render_to_response(template_name, {'mainForm': mainForm, 'contactsForm': contactsForm, 'placeFormSet': placeFormSet, 'errors': errors, 'success': success}, context_instance=user_context(request))

edit_profile = login_required(redirect_field_name='/profile/edit/')(edit_profile)

def view_profile(request, template_name, id=None):
    #
    # Показывает профиль
    # если id == None, отобразится текущий профиль
    # если id != None, то отобразится профиль с pk=id
    #
    profile = get_object_or_404(UserProfile, pk__exact=int(id)) if id is not None else request.profile
    places = {}
    for p in profile.get_places_list():
        try:
            places[p.place_type].append(p)
        except KeyError:
            places[p.place_type] = [p]
    current_profile = request.profile
    can_add_friendship = (not profile in current_profile.get_friends_list()) and (Friendship.objects.filter(_from=current_profile) is None)
    can_del_friendship = profile in current_profile.get_friends_list()
    can_attach = False
    if current_profile.position is not None:
        if profile.position is not None:
            can_attach = profile.position.position_type.weight < current_profile.position.position_type.weight
        else:
            can_attach = current_profile.position.position_type.weight > 2
    return render_to_response(template_name, {'can_add_friendship': can_add_friendship, 'can_del_friendship': can_del_friendship, 'userprofile': profile, 'places': places, 'can_attach': can_attach}, context_instance=user_context(request))

view_profile = login_required(redirect_field_name='/profile/')(view_profile)

def view_list_profile(request, template_name, search=True, id=None):
    if id is None:
        if request.method == 'POST':
            form = UserProfileSearchForm(request.POST)
            if form.is_valid():
                L34 = form.clean_L34Object()
                data = form.cleaned_data
                query = Q()
                    
                if data.get('first_name', False):
                    query.add(Q(first_name__icontains=data.get('first_name', False)), Q.AND)
                if data.get('last_name', False):
                    query.add(Q(last_name__icontains=data.get('last_name', False)), Q.AND)
                if data.get('birth_date', False):
                    query.add(Q(birth_date__exact=data.get('birth_date', False)), Q.AND)
                if L34 is not None:
                    query.add(Q(contact_L34Object__exact=L34), Q.AND)
                    
                profiles = UserProfile.objects.filter(query)[0:100]  
                      
                paginator = Paginator(profiles, 10)
                try:
                    page = int(request.GET.get('page', '1'))
                except ValueError:
                    page = 1
                try:
                    pages = paginator.page(page)
                except (EmptyPage, InvalidPage):
                    pages = paginator.page(paginator.num_pages)
                    
                return render_to_respond(template_name, {'form': form, 'profiles': profiles, 'pages': pages}, context_instance=user_context(request))
            else:    
                return render_to_respond(template_name, {'form': form}, context_instance=user_context(request))
        else:
            form = UserProfileSearchForm()
            return render_to_respond(template_name, {'form': form}, context_instance=user_context(request))
    else:
        if int(id) == request.profile.id:
            profile = request.profile
            fship_senders = profile.get_friendship_senders_list()
        else:
            profile = get_object_or_404(UserProfile, pk=id)
        profiles_list = profile.get_friends_list()
        paginator = Paginator(profiles_list, 10)
        try:
            page = int(request.GET.get('page', '1'))
        except ValueError:
            page = 1
        try:
            profiles = paginator.page(page)
        except (EmptyPage, InvalidPage):
            profiles = paginator.page(paginator.num_pages)
        return render_to_response(template_name, {'userprofile': profile, 'friendships': fship_senders, 'profiles': profiles}, context_instance=user_context(request))
            
def search_profile(request, template_name, query):
    pass